package com.muqi.app.qlearn.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.adapter.HomeWorkAdapter;
import com.muqi.app.qlearn.modles.Banner;
import com.muqi.app.qlearn.modles.HomeWorkBean;
import com.muqi.app.qlearn.modles.HomeWorkFile;
import com.muqi.app.qlearn.modles.LastRecord;
import com.muqi.app.qlearn.student.BaseFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.HomeWorkStatisticActivity;
import com.muqi.app.qlearn.ui.MyHomeWkDetailsActivity;
import com.muqi.app.qlearn.ui.MyHomeWorkActivity;
import com.muqi.app.user.widget.SelectableRoundedImageView;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.muqi.app.widget.scanpicture.ScanPictureActivity;

@SuppressLint("InflateParams")
public class HomeWorkFragment extends BaseFragment implements
		XListView.IXListViewListener, HomeWorkAdapter.OnHomeWorkListener,
		OnItemClickListener {
	public static final int UPDATE_HOMEWORK_BEANS = 10005;
	private XListView mListview;
	private HomeWorkAdapter mAdapter = null;
	private List<HomeWorkBean> homewks = new ArrayList<HomeWorkBean>();
	private int page = 1;
	private int lastClickposition = -1;
	private boolean isNotification;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.aty_my_homework, null);
		initView(view);
		return view;
	}

	private void initView(View view) {
		mListview = (XListView)view.findViewById(R.id.xListView);
		mListview.setXListViewListener(this);
		mListview.setPullLoadEnable(false);
		mListview.setPullRefreshEnable(true);
		mListview.setOnItemClickListener(this);
		View headerView = LayoutInflater.from(mActivity).inflate(
				R.layout.header_view_homework, null);
		mListview.addHeaderView(headerView);
		headerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(HomeWorkStatisticActivity.class);
			}
		});
		loadingServiceDatas();
	}
	private void loadingServiceDatas() {
		if (NetWorkUtils.isNetworkAvailable(mActivity)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			sendMap.put("page", page);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_MY_HOMEWORK_LISTS_API, sendMap);
			MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					onLoadView();
					hideLoading();
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<HomeWorkBean> getLists = ResponseUtils
								.getMyHomeworkLists(mActivity, result);
						if (getLists != null && getLists.size() > 0) {
							if (page == 1) {
								if (getLists.size() == 0) {
									showEmpty("还没有收到任何作业");
									return;
								} else {
									hidEmpty();
								}
								homewks.clear();
								homewks = getLists;
								if (mAdapter != null)
									mAdapter = null;
								mAdapter = new HomeWorkAdapter(mActivity,
										homewks, HomeWorkFragment.this);
								mListview.setAdapter(mAdapter);
							} else {
								for (HomeWorkBean item : getLists) {
									homewks.add(item);
								}
								mAdapter.notifyDataSetChanged();
							}
							if (getLists.size() < 10) {
								mListview.setPullLoadEnable(false);
							} else {
								mListview.setPullLoadEnable(true);
								page++;
							}
						}
					}
				}
			});
		} else {
			hideLoading();
			ShowToast.showShort(mActivity, R.string.net_break);// 提示无网络
		}
	}

	private void onLoadView() {
		mListview.stopRefresh();
		mListview.stopLoadMore();
		mListview.setRefreshTime("刚刚");
	}

	@Override
	public void onRefresh() {
		page = 1;
		loadingServiceDatas();
	}

	@Override
	public void onLoadMore() {
		loadingServiceDatas();
	}

	@Override
	public void onClickPhoto(int parentPosition, int sonPosition) {
		List<String> bigUrls = new ArrayList<String>();
		for (HomeWorkFile info : homewks.get(parentPosition).classJobFiles) {
			bigUrls.add(info.fileurlInfo.fileurl_03);
		}
		if (bigUrls.size() > 0) {
			Intent intent = new Intent(mActivity, ScanPictureActivity.class);
			intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_URLS,
					(ArrayList<String>) bigUrls);
			intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_INDEX, sonPosition);
			startActivity(intent);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (homewks != null && position >= 2) {
			Intent intent = new Intent(mActivity, MyHomeWkDetailsActivity.class);
			intent.putExtra(MyHomeWkDetailsActivity.HOMEWORK_ID,
					homewks.get(position - 2).class_job_id);
			intent.putExtra(MyHomeWkDetailsActivity.HOMEWORK_DETAILS,
					homewks.get(position - 2));
			startActivityForResult(intent, UPDATE_HOMEWORK_BEANS);
			lastClickposition = position - 2;
		}

	}

	@Override
	public void onActivityResult(int reqest, int result, Intent intent) {
		super.onActivityResult(reqest, result, intent);
		if (reqest == UPDATE_HOMEWORK_BEANS) {
			if (result ==Activity.RESULT_OK) {
				if (intent != null) {
					HomeWorkBean bean = (HomeWorkBean) intent
							.getSerializableExtra(MyHomeWkDetailsActivity.HOMEWORK_CONFIRM_TYPE);
					Log.e("===",
							bean.getConfirmState() + " " + bean.getWithState());
					if (lastClickposition != -1 && bean != null) {
						homewks.set(lastClickposition, bean);
						if (mAdapter != null)
							mAdapter.notifyDataSetChanged();
						// onRefresh();
					}
				}
				return;
			}

		}
	}



	@Override
	public void onClickDelete(int position) {
		deleteHomeWork(position);

	}

	private void deleteHomeWork(final int position) {
		showLoading();
		HomeWorkBean bean = homewks.get(position);
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("class_job_id", bean.class_job_id);
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		String requestUrl = ParamsUtils.buildParams(NetWorkApi.DELET_HOME_WORK,
				sendMap);
		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {
			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				// Log.e("===", result);
				if (resuleCode == RESULTCODE.SUCCESS) {
					homewks.remove(position);
					if (mAdapter != null)
						mAdapter.notifyDataSetChanged();
					hideLoading();
					Toast.makeText(mActivity, "删除成功", Toast.LENGTH_SHORT).show();
				}
			}
		});

	}
}